import Bus from '@/utils/Bus'
export default ({ app, redirect }) => {
  app.router.beforeEach((to, from, next) => {
    let _channel = null
    let unique_id = null
    if (from.query && from.query._channel) {
      _channel = from.query._channel
    }
    if (from.query && from.query._channel) {
      unique_id = from.query.unique_id
    }
    const fullPath = to.fullPath.split('?')
    const lastStr = fullPath[0][fullPath[0].length - 1]
    let query = ''
    if (lastStr === '/' && to.path !== '/') {
      query = fullPath[1] ? '?' + fullPath[1] : ''
    } else {
      query = fullPath[1] ? '/?' + fullPath[1] : '/'
    }
    if (!fullPath[1]) {
      if (query.indexOf('_channel') < 0 && _channel) {
        query += `?_channel=${_channel}`
      }
    } else {
      if (query.indexOf('_channel') < 0 && _channel) {
        query += `&_channel=${_channel}`
      }
    }
    if (query.indexOf('unique_id') < 0 && unique_id) {
      query += `&unique_id=${unique_id}`
    }
    const toQ = fullPath[1] || ''
    let url = ''
    if (fullPath[0] === '/') {
      url = query
    } else {
      url = fullPath[0] + query
    }
    if (to.name !== 'aboutus' && to.name !== 'aboutUs') {
      if ((_channel && toQ.indexOf('_channel') < 0) || (unique_id && toQ.indexOf('unique_id') < 0)) {
        return redirect(url)
      } else if (Object.keys(to.params).length === 0 && lastStr !== '/') {
        return redirect(url)
      }
      next()
    } else {
      Bus.$emit('open')
    }
  })
}
